import da from "element-ui/src/locale/lang/da";


export { uploadFile, downloadFile } from './file'
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";

/**
 * @description 更新标题
 * @param {String} title 标题
 */
export const title = function (titleText) {
  window.document.title = `${titleText ? `${titleText}` : ''}`
}

/**
 * @description 打开新页面
 * @param {String} url 地址
 */
export const open = function (url) {
  var a = document.createElement('a')
  a.setAttribute('href', url)
  a.setAttribute('rel', 'noopener')
  a.setAttribute('target', '_blank')
  a.setAttribute('id', 'myadmin-link-temp')
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(document.getElementById('myadmin-link-temp'))
}
import { cloneDeep } from 'lodash'

export const sandbox = function (obj) {
  let tar = cloneDeep(obj)

  return new Proxy(tar, {
    get (t, p) {
      if (p === 'reset') {
        return () => {
          for (const key in tar) {
            // eslint-disable-next-line no-prototype-builtins
            if (obj.hasOwnProperty(key)) {
              tar[key] = obj[key]
            } else {
              delete tar[key]
            }
          }
          if (Array.isArray(tar)) {
            // 为空的元素挪到数组末尾,为空的元素不会被数组方法迭代
            tar.sort(() => 1)
            let nulls = 0
            // 判断不为空的元素的长度
            tar.forEach(i => i && nulls++)
            tar.length = nulls
          }
        }
      } else {
        return tar[p]
      }
    }
  })
}


/**
 * @description: htmlToPdf
 * @param {String} ele dom
 * @param {String} title 地址
 */
export function htmlToPdf (ele, title) {
  const dom = document.querySelector('#' + ele)
  return html2Canvas(dom, {
    useCORS: true,//解决网络图片跨域问题
    width: dom.width,
    height: dom.height,
    windowWidth: dom.scrollWidth,
    dpi: window.devicePixelRatio * 4, // 将分辨率提高到特定的DPI 提高四倍
    scale: 4, // 按比例增加分辨率
  }).then((canvas) => {
    // eslint-disable-next-line new-cap
    const pdf = new JsPDF('p', 'mm', 'a4'); // A4纸，纵向
    const ctx = canvas.getContext('2d');
    const a4w = 170;
    const a4h = 250; // A4大小，210mm x 297mm，四边各保留20mm的边距，显示区域170x257
    const imgHeight = Math.floor(a4h * canvas.width / a4w); // 按A4显示比例换算一页图像的像素高度
    let renderedHeight = 0;

    while (renderedHeight < canvas.height) {
      const page = document.createElement('canvas');
      page.width = canvas.width;
      page.height = Math.min(imgHeight, canvas.height - renderedHeight);// 可能内容不足一页

      // 用getImageData剪裁指定区域，并画到前面创建的canvas对象中
      page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0);
      pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 20, 20, a4w, Math.min(a4h, a4w * page.height / page.width)); // 添加图像到页面，保留10mm边距

      renderedHeight += imgHeight;
      if (renderedHeight < canvas.height) {
        pdf.addPage();// 如果后面还有内容，添加一个空页
      }
      // 预览pdf(这里我用的是事件总线把canvas传递过去展示，达到模拟pdf预览的效果，有用但效果不是很好，有需要的可以自行修改)
      //this.$EventBus.$emit('open-pdf', canvas);
    }

    return putFile(pdf,`${title}`)
    function putFile(PDF, fileName) {
      // 用于测试 PDF.save(`${fileName}.pdf`)
      let file = convertBase64ToFile(PDF.output("dataurlstring"), fileName);
      return file
    }

    function convertBase64ToFile(urlData, filename) {
      var arr = urlData.split('base64,');
      var type = arr[0].match(/:(.*?);/)[1];
      var fileExt = type.split('/')[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename + "." + fileExt, {
        type: type
      });
    }

    // 下载文件
    // pdf.save(`${title}.pdf`);
  });
}


/**
 * @description: addRule
 * @param {String} type
 */
export function addRule (type) {
  let data = {}
  if(type === 'ruleItem'){
    data = {
      categoryDesc:'',
      categoryName:'',
      ruleList:[
        {
          calcType:null,
          categoryId:'',
          children:[
            {
              calcType:null,
              categoryId:'',
              id:null,
              item:'',
              itemDesc:'',
              itemIs:'',
              itemIsArry:null,
              logicalOperator:'或',
              orgId:null,
              pid:null,
              rangeValue1:null,
              rangeValue2:null,
              tagId:null,
            },
          ],
          id:null,
          item:'',
          itemDesc:'',
          itemIs:'',
          itemIsArry:null,
          logicalOperator:'且',
          orgId:null,
          pid:null,
          rangeValue1:null,
          rangeValue2:null,
          tagId:null,
        }
      ]
    }
  }
  if(type === 'also'){
    data = {
      calcType:null,
      categoryId:'',
      children:[
        {
          calcType:null,
          categoryId:'',
          id:null,
          item:'',
          itemDesc:'',
          itemIs:'',
          itemIsArry:null,
          logicalOperator:'或',
          orgId:null,
          pid:null,
          rangeValue1:null,
          rangeValue2:null,
          tagId:null,
        },
      ],
      id:null,
      item:'',
      itemDesc:'',
      itemIs:'',
      itemIsArry:null,
      logicalOperator:'且',
      orgId:null,
      pid:null,
      rangeValue1:null,
      rangeValue2:null,
      tagId:null,
    }
  }
  if(type === 'or'){
    data = {
      calcType:null,
      categoryId:'',
      id:null,
      item:'',
      itemDesc:'',
      itemIs:'',
      itemIsArry:null,
      logicalOperator:'或',
      orgId:null,
      pid:null,
      rangeValue1:null,
      rangeValue2:null,
      tagId:null,
    }
  }
  return data
}